import { ScrollView, StyleSheet, Text, View } from "react-native";
import React, { useContext, useState } from "react";
import { SafeAreaView } from "react-native-safe-area-context";
import Head from "../../components/Head";
import { Button, HelperText, TextInput } from "react-native-paper";
import { Https } from "../../api";

import { useStoreObject, useStoreString } from "../../hooks/useStorage";
import { useToast } from "react-native-toast-notifications";
import { GlobalContext } from "../../hooks/reducer";
import { StackActions, useNavigation } from "@react-navigation/native";
const Login = () => {
  const toast = useToast();
  const [phone, setPhone] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const navigation = useNavigation();
  const changeState: any = useContext(GlobalContext);
  const [phoneErrorVisible, setPhoneErrorVisible] = useState({
    Visible: false,
    title: "请输入手机号",
  });
  const [passwordErrorVisible, setPasswordErrorVisible] = useState({
    Visible: false,
    title: "请输入密码",
  });
  const [secureTextEntry, setSecureTextEntry] = useState(true);

  const handleLogin = async () => {
    if (phone && password) {
      if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(phone)) {
        changeState.dispatch({ type: "SetToLoad", payload: true });
        const { succeed, data, msg } = await Https.userLogin({
          phone,
          password,
        });
        changeState.dispatch({ type: "SetToLoad", payload: false });
        if (succeed) {
          const { token, result } = data;
          useStoreString("token", token);
          useStoreObject("userInfo", result);
          console.log(result);
          
          toast.show(`欢迎回来，${phone}`, {
            type: "normal",
            placement: "bottom",
            animationType: "slide-in",
            textStyle: { fontSize: 16 },
          });
          setTimeout(() => {
            toast.hideAll();
            StackActions.replace("Login");
            navigation.navigate("Mine");
          }, 500);
          return;
        }
        toast.show(msg, {
          type: "danger",
          placement: "bottom",
          duration: 3000,
          // offset: 30,
          animationType: "slide-in",
          textStyle: { fontSize: 16 },
        });
        return;
      }
      setPhoneErrorVisible({ Visible: true, title: "您的手机号有误" });
      return;
    }
    !phone &&
      setPhoneErrorVisible({ Visible: true, title: "请输入完整手机号" });
    !password &&
      setPasswordErrorVisible({ Visible: true, title: "请输入密码" });
  };

  const changeText = (value: string, type: string) => {
    switch (type) {
      case "phone":
        setPhone(value);
        setPhoneErrorVisible({ Visible: false, title: "" });
        break;
      case "password":
        setPassword(value);
        setPasswordErrorVisible({ Visible: false, title: "" });
        break;
    }
  };

  return (
    <SafeAreaView style={{ backgroundColor: "#fff", flex: 1 }}>
      <Head />
      <ScrollView
        showsVerticalScrollIndicator={false}
        keyboardDismissMode={"on-drag"}
      >
        <View style={styles.loginMain}>
          <TextInput
            label="手机号码"
            mode="outlined"
            placeholder="请输入手机号码"
            selectionColor="#000"
            activeOutlineColor="#000"
            keyboardType="number-pad"
            maxLength={11}
            style={{ backgroundColor: "#f8f9fa" }}
            value={phone}
            onChangeText={(text) => changeText(text, "phone")}
          />
          <HelperText type="error" visible={phoneErrorVisible.Visible}>
            {phoneErrorVisible.title}
          </HelperText>
          <TextInput
            label="密码"
            mode="outlined"
            placeholder="请输入密码"
            selectionColor="#000"
            activeOutlineColor="#000"
            maxLength={20}
            secureTextEntry={secureTextEntry}
            style={{ backgroundColor: "#f8f9fa" }}
            value={password}
            onChangeText={(text) => changeText(text, "password")}
            right={
              <TextInput.Icon
                icon="eye"
                onPressOut={() => setSecureTextEntry(!secureTextEntry)}
              />
            }
          />
          <HelperText type="error" visible={passwordErrorVisible.Visible}>
            {passwordErrorVisible.title}
          </HelperText>
          <Button
            color={"#fff"}
            mode="contained"
            buttonColor={"#000"}
            textColor={"#fff"}
            compact={true}
            style={{ borderRadius: 5, marginTop: 50 ,paddingVertical:5}}
            labelStyle={{ fontSize: 16 }}
            //   contentStyle={{ ...styles.BottomButton, ...styleAll.iosBottom }}
            onPress={() => handleLogin()}
          >
            立即登陆/注册
          </Button>
        </View>
        <Text style={{ textAlign: "center" }}>
          2013 Bestseller.All Right Reserved
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
};

export default Login;

const styles = StyleSheet.create({
  loginMain: {
    width: "85%",
    height: 500,
    marginLeft: "7.5%",
    marginTop: 100,
  },
});
